package T01_test_all.test10_Student;

public class T10_StudentTest {
    public static void main(String[] args) {
        // 1、对一组数据添加一条数据
        // 2、遍历输出数据

        T10_Student[] arr = new T10_Student[3];

        T10_Student stu1 = new T10_Student(1, "xh", 18);
        T10_Student stu2 = new T10_Student(2, "lirong", 18);
        T10_Student stu3 = new T10_Student(3, "tudou", 18);

        arr[0] = stu1;
        arr[1] = stu2;
        arr[2] = stu3;

        T10_Student stu4 = new T10_Student(4, "guoguo", 24);

        //添加新数据 判断是否存在
        boolean flag = contain(arr, stu4.getId());
        if (flag) {
            //存在
            System.out.println("当前id重复，请修改id后进行添加");
        } else {
            //首先判断数组 是否存满
            int count = getCount(arr);
            if (count == arr.length) {
                // 存满了
                T10_Student[] newArr = creatNewArr(arr);
                newArr[count] = stu4;
                printArr(newArr);
            } else {
                // 没有满, 存数据
                arr[count] = stu4;
                printArr(arr);
            }
        }
    }

    /***
     * 遍历输出
     * @param arr
     */
    public static void printArr(T10_Student[] arr){
        for (int i = 0; i < arr.length; i++) {
            T10_Student stu = arr[i];
            if(stu != null){
                System.out.println(stu.getId()+ " " + stu.getName() + " " + stu.getAge());
            }
        }
    }

    /***
     * 创建一个新的列表
     * @param arr
     * @return
     */
    public static T10_Student[] creatNewArr(T10_Student[] arr) {
        T10_Student[] newArr = new T10_Student[arr.length + 1];
        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }
        return newArr;
    }

    /***
     * 获取列表数据长度
     * @param arr
     * @return
     */
    public static int getCount(T10_Student[] arr) {
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != null) {
                count++;
            }
        }
        return count;
    }

    /***
     * 数据是否存在
     * @param arr
     * @param id
     * @return
     */
    public static boolean contain(T10_Student[] arr, int id) {
        for (int i = 0; i < arr.length; i++) {
            T10_Student stu = arr[i];
            if(stu != null){
                int sid = stu.getId();
                if (sid == id) {
                    return true;
                }
            }

        }
        return false;
    }
}
